﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using AAA.Meta.Command;
using AAA.Base.Util.Json;
using AAA.Base.Util.WCF;

namespace AAA.Communication.WCFService
{
    public class WCFCommandClient
    {
        ChannelFactory<ICommandService> _factory;
        private ICommandService _proxy;
        private bool _isConnected;

        public string Url
        {
            get { return _factory.Endpoint.Address.Uri.AbsoluteUri; }
        }

        public bool IsConnected
        {
            get { return _isConnected; }
        }

        public void Connect(string strUrl)
        {
            Connect(strUrl, strUrl.Split(':')[0]);
        }

        public void Connect(string strUrl, string strProtocol)
        {
            try
            {
                Uri address = new Uri(strUrl);
                System.ServiceModel.Channels.Binding binding = WCFUtil.CreateBinding(strProtocol);
                _factory = new ChannelFactory<ICommandService>(binding, new EndpointAddress(address));
                _proxy = _factory.CreateChannel();
                _isConnected = true;
            }
            catch (Exception ex)
            {
                _isConnected = false;
            }

        }

        public void Disconnect()
        {
            if (!_isConnected) return;
            try
            {
                _factory.Abort();
                _factory.Close();
                _isConnected = false;
            }
            catch (Exception ex)
            {

            }
        }

        public CommandProfile ExecuteCommand(CommandProfile cCommmandProfile)
        {
            if (!_isConnected) return null;
            string strProfile = _proxy.ExecuteCommand(JsonUtil.Serialize(cCommmandProfile));
            return JsonUtil.Deserialize<CommandProfile>(strProfile);
        }

    }
}
